package org.github.core.spring.restful.json;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.google.common.net.MediaType;
import javax.annotation.Nullable;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import static cn.hutool.core.text.CharSequenceUtil.firstNonBlank;
import static cn.hutool.extra.servlet.ServletUtil.write;
import static com.google.common.net.MediaType.JAVASCRIPT_UTF_8;
import static org.github.core.Const.CALLBACK;

/**
 * JSON of jsonp.
 *
 * @param <T> data
 * @author JYD_XL
 * @see java.io.Serializable
 * @see java.util.function.Supplier
 */
@EqualsAndHashCode(callSuper = true)
@AllArgsConstructor
@NoArgsConstructor
@Data
public class JSONPData<T> extends JSONBase implements JSON {
  /** 数据 */
  @Nullable
  private T data;

  /** 回调函数 */
  @JsonIgnore
  @NotNull
  private String callback = CALLBACK;

  @Override
  public void handle(@NotNull HttpServletRequest req, @NotNull HttpServletResponse res) {
    if (CALLBACK.equals(callback)) setCallback(firstNonBlank(req.getParameter(CALLBACK), CALLBACK));
    write(res, get(), mediaType().toString());
  }

  @Override
  @NotNull
  public String get() {
    return callback + "(" + super.get() + ")";
  }

  @Override
  public String toString() {
    return super.toString();
  }

  @Override
  @NotNull
  public MediaType mediaType() {
    return JAVASCRIPT_UTF_8;
  }

  /**
   * Generator.
   */
  @NotNull
  public static <T> JSONPData<T> of() {
    return new JSONPData<>();
  }

  /**
   * Generator.
   */
  @NotNull
  public static <T> JSONPData<T> of(T data) {
    return new JSONPData<>(data, CALLBACK);
  }

  /**
   * Generator.
   */
  @NotNull
  public static <T> JSONPData<T> of(T data, String callback) {
    return new JSONPData<>(data, firstNonBlank(callback, CALLBACK));
  }
}
